package com.celebriosoftware.client.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.BatteryManager;
import android.util.Log;

import com.celebriosoftware.client.MainActivity;
import com.celebriosoftware.client.fragments.DesktopFragment;

public class BatteryReceiver extends BroadcastReceiver {

	private int level = -1;
	private int status = -1;
	private int batteryState = 4;
	private DesktopFragment fragment = null;
	
	public BatteryReceiver() {
	}
	public BatteryReceiver(DesktopFragment fragment) {
		this.fragment = fragment;
	}
	
	@Override
	public void onReceive(Context context, Intent intent) {
		level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
		status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
		boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING;
		if (isCharging) {
			Log.i("Celebrio-Battery", "Charging");
		}
		if (level > 80) {
			batteryState = 4;
		}
		else if (level > 60) {
			batteryState = 3;
		}
		else if (level > 40) {
			batteryState = 2;
		}
		else if (level > 20) {
			batteryState = 1;
		}
		else if (level > 5) {
			batteryState = 0;
		}
		else if (level > 0) {
			batteryState = -1;
		}
		reportBatteryState();
	}
	
	private void reportBatteryState() {
		if(fragment != null) {
			fragment.updateBatteryState(batteryState);
		}
		else {
			Log.w("battery receiver", "parent activity not supplied");
		}
	}
	
	public int getBatteryState(){
		return batteryState;
	}
}
